<script lang="ts" setup>
import { Snackbar } from "@varlet/ui";
import { applyLink } from "~/api/link";
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:show"]);
const loading = ref(false);
const input = ref({
  name: undefined as string | undefined,
  link: undefined as string | undefined,
  email: undefined as string | undefined,
});
async function submit() {
  const { email, link, name } = input.value;
  if (!email || !link || !name) {
    Snackbar.error("请填写完整信息");
    return;
  }
  const reg = /@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  if (!reg.test(email)) {
    Snackbar.error("邮箱不合法！");
    return;
  }
  loading.value = true;
  applyLink(input.value as any)
    .then(() => {
      Snackbar.success("申请成功！审核通过后会邮件通知您！");
      emit("update:show", false);
    })
    .catch((err) => {
      Snackbar.error("申请失败！" + err);
    })
    .finally(() => {
      loading.value = false;
    });
}
</script>

<template>
  <ClientOnly>
    <var-overlay :show="props.show">
      <var-form
        ref="form"
        class="box"
        scroll-to-error="start"
        @submit="submit()"
      >
        <var-space
          direction="column"
          :size="[14, 0]"
        >
          <h2>申请友链</h2>

          <var-input
            variant="outlined"
            size="small"
            placeholder="请输入名称"
            :rules="[(v) => !!v || '名称不能为空']"
            v-model="input.name"
          >
          </var-input>
          <var-input
            variant="outlined"
            size="small"
            placeholder="请输入链接"
            :rules="[(v) => !!v || '链接不能为空']"
            v-model="input.link"
          >
          </var-input>
          <var-input
            variant="outlined"
            size="small"
            placeholder="请输入邮箱"
            :rules="[(v) => !!v || '邮箱不能为空']"
            v-model="input.email"
          >
          </var-input>
          <div style="display: flex; gap: 1em">
            <var-button
              style="flex: 1"
              :loading="loading"
              loading-type="wave"
              type="primary"
              native-type="submit"
              >申 请</var-button
            >
            <var-button
              style="flex: 1"
              text
              :loading="loading"
              loading-type="wave"
              type="default"
              native-type="reset"
              @click="emit('update:show', false)"
              >返 回</var-button
            >
          </div>
        </var-space>
      </var-form>
    </var-overlay>
  </ClientOnly>
</template>

<style lang="less" scoped>
.box {
  padding: 0.8em;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-radius: 0.5em;
  background-color: var(--color-body);
  box-shadow: 0 0 1em 0 rgb(0 0 0 / 0.1);
}
</style>
